package com.lollipop.chain.advancedchain;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: J.K
 * @Date: 2021-08-31 14:13
 * @Description:
 */
public class FilterChain implements Filter {

    List<Filter> filters = new ArrayList<>();
    int index = 0;

    public FilterChain addFilter(Filter f) {
        this.filters.add(f);
        return this;
    }

    /**
     * 添加过滤器
     * 支持链式添加的方法：返回FilterChain本身
     *
     * @param request
     * @param response
     * @param chain
     */
    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {
        if (index == filters.size()) {
            return;
        }

        // 获取当前的过滤器
        Filter f = filters.get(index);
        // 指向下个过滤器的索引
        index++;
        // 执行当前过滤器的方法
        f.doFilter(request, response, chain);
    }
}
